package com.withoutwords.ui;

import java.util.ArrayList;
import java.util.Collections;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.withoutwords.R;
import com.withoutwords.engine.BitmapCache;
import com.withoutwords.engine.Common;
import com.withoutwords.engine.Game;
import com.withoutwords.engine.GameController;
import com.withoutwords.engine.MyInfo;
import com.withoutwords.engine.comminication.CommunicationManager;
import com.withoutwords.engine.comminication.IServerResultListener;
import com.withoutwords.engine.comminication.ServerRequests;
import com.withoutwords.engine.settings.Settings;
import com.withoutwords.engine.social.ISocialNetworkController;
import com.withoutwords.engine.social.SocialEngine;
import com.withoutwords.engine.social.SocialUser;
import com.withoutwords.engine.social.SocialNetwork;
import com.withoutwords.engine.social.listeners.ISocialFriendListListener;
import com.withoutwords.ui.custom.MyCustomButton;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.Toast;

public class CreateGameActivity extends BaseActivity implements
		OnClickListener, ISocialFriendListListener, IServerResultListener {

	ISocialNetworkController fbController;
	
	Game game;
	ArrayList<SocialUser> friendList;
	ProgressBar pBarWait;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.creategame);
		/*
		 * LinearLayout ly = (LinearLayout) findViewById(R.id.lyCreate); if (ly
		 * != null) { ly.setBackgroundDrawable(BitmapCache
		 * .getCacheInstance().getDrawable(R.drawable.intro)); }
		 */

		MyCustomButton btn = (MyCustomButton) findViewById(R.id.btnStartGame);
		btn.setOnClickListener(this);
		btn.setEnabled(false);
		fbController = SocialEngine.getSocialEngine()
				.getSocialNetworkController(SocialNetwork.Facebook);
		fbController.readFriendList(this, true);
		pBarWait = (ProgressBar) findViewById(R.id.progressBarWait);

		uiHandler = new Handler();

	}

	@Override
	protected void setBitmaps() {
		// TODO Auto-generated method stub
		super.setBitmaps();
		setLayoutBitmap(R.id.lyBlackboard, R.drawable.blackboard);

	}

	@Override
	protected void unsetBitmaps() {
		// TODO Auto-generated method stub
		super.unsetBitmaps();
		unsetLayoutBitmaps(R.id.lyBlackboard);

	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btnStartGame: {
			ListView lv = (ListView) findViewById(R.id.lstFriends);
			if (lv != null) {
				long[] itemIds = lv.getCheckItemIds();
				if (itemIds.length >= 1) {
					game = new Game();

					for (int i = 0; i < itemIds.length; i++) {
						game.addPlayer(friendList.get((int) itemIds[i]));

					}

					MyInfo me = Settings.getInstance().getMyInfo();
					if (me != null) {
						game.setGameOwner(me.getSocialUser());
					}

					// temp to test push notifications
					// game.addPlayer(me.getSocialUser());

					GameController.getInstance().createGame(game);

					pBarWait.setVisibility(View.VISIBLE);
					// v.setEnabled(false);
				}

				else {
					Toast.makeText(this,
							getResources().getString(R.string.select_friends),
							Toast.LENGTH_LONG).show();
				}
			}
			// finish();
			break;
		}
		}

	}

	@Override
	protected void releaseBitmaps() {
		// TODO Auto-generated method stub
		super.releaseBitmaps();
		/*
		 * BitmapCache .getCacheInstance().deleteDrawable(R.drawable.intro);
		 */
		BitmapCache.getCacheInstance().deleteDrawable(R.drawable.blackboard);
	}

	@Override
	public void onFriendListRecieved(final ArrayList<SocialUser> friendlist) {

		
		this.friendList = friendlist;
		/*
		 * Bundle data = new Bundle(); data.putSerializable("friendlist",
		 * friendlist);
		 */
		Bundle bundle = new Bundle();
		JSONArray arrayJson = new JSONArray();

		for (int i = 0; i < friendlist.size(); i++) {
			try {
				arrayJson.put(i, friendlist.get(i).toJSON());
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		JSONObject obj = new JSONObject();
		try {
			obj.put(Common.usersCode, arrayJson);
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		String objStr = obj.toString();
		bundle.putString(Common.usersCode, objStr);

		CommunicationManager.getCommnuicationManager().request(this,
				ServerRequests.getRegisteredUser, bundle, this);

		

	}

	void handleError(final String errorString) {
		
				pBarWait.setVisibility(View.GONE);
				
				finish();
			

	}
	void startLoginActivity()
	{
		startActivity(new Intent(getApplicationContext(),
				LoginActivity.class));
		finish();
	}
	@Override
	public void onError(final String error) {
		if(error.contains("OAuthException"))
		{
			SocialEngine.getSocialEngine().logout(this);
			Settings.getInstance().setMyInfo(new MyInfo(), true);
			startLoginActivity();

			Toast.makeText(this,
					getString(R.string.facebook_expired_error), Toast.LENGTH_LONG).show();
		}
		else
		handleError(error);
	}

	void updateListWithFriends(ArrayList<SocialUser> friendlist) {
		pBarWait.setVisibility(View.GONE);
		// set layout visible to begin animation
		findViewById(R.id.friendListLayout).setVisibility(View.VISIBLE);

		playSound(soundResId);
		Collections.sort( friendlist);
		this.friendList = friendlist;
		ListView lv = (ListView) findViewById(R.id.lstFriends);
		if (lv != null && friendlist != null) {
			lv.setAdapter(new ArrayAdapter<SocialUser>(CreateGameActivity.this,
					R.layout.custom_list_item_multiple_choice, friendlist));// (ArrayList<SocialUser>)
																			// response.get("friendList")));
			lv.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
			lv.invalidate();
			MyCustomButton btn = (MyCustomButton) findViewById(R.id.btnStartGame);
			// btn.setOnClickListener(this);
			btn.setEnabled(true);
		}
	}

	@Override
	public void onRequestSucceed(ServerRequests serverRequest,
			final Bundle response) {
		switch (serverRequest) {
		case getRegisteredUser:
			uiHandler.post(new Runnable() {

				@Override
				public void run() {
					updateListWithFriends((ArrayList<SocialUser>) response
							.get(Common.usersCode));

				}
			});
			break;

		default:
			break;
		}

	}

	@Override
	public void onRequestFailed(ServerRequests serverRequest, final String error) {
		uiHandler.post(new Runnable() {

			@Override
			public void run() {
		// TODO Auto-generated method stub
		CreateGameActivity.super.OnError(error);
		handleError(error);
			}
		});
	}
	@Override
	public void OnError(final String Error) {
		uiHandler.post(new Runnable() {

			@Override
			public void run() {
		// TODO Auto-generated method stub
		CreateGameActivity.super.OnError(Error);
		handleError(Error);
			}
		
	});
	}

}
